package com.moorecat.app;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.moorecat.MooerApplication;
import com.moorecat.R;
import com.moorecat.http.HttpUtils;
import com.moorecat.utils.ui.BitmapViewBinder;
import com.moorecat.utils.ui.ImageUtils;
import com.moorecat.utils.ui.ProgressLinearLayout;
import com.moorecat.utils.ui.UiUtils;

/**
 * @author pengfei.xu
 * @version 创建时间：2011-6-22 下午02:04:53 类说明
 */
public class ActivityDetail extends Activity implements OnClickListener,
		OnScrollListener {

	private static final String TAG = "ActivityDetail";

	private ImageView sign, remark;

	private ListView listView;

	private ImageView activityPic;

	private TextView activityName, activityRequire;

	private ActivityCommentAdapter adapter;

	private ProgressLinearLayout footer;

	private List<com.moorecat.bean.Comment> list = new ArrayList<com.moorecat.bean.Comment>();

	private Intent intent;

	private long taskId;

	private MooerApplication mooerApp;

	private AsyncTask bitmapTask;

	private boolean isCancelled;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_detail);
		mooerApp = (MooerApplication) getApplication();
		intent = getIntent();
		activityName = (TextView) findViewById(R.id.activity_name);
		activityRequire = (TextView) findViewById(R.id.activity_require);
		sign = (ImageView) findViewById(R.id.sign);
		remark = (ImageView) findViewById(R.id.remark);
		activityPic = (ImageView) findViewById(R.id.activity_pic);
		listView = (ListView) findViewById(R.id.listview);
		footer = (ProgressLinearLayout) LayoutInflater.from(this).inflate(
				R.layout.progress_small, null);
		footer.initView();
		listView.addFooterView(footer);
		adapter = new ActivityCommentAdapter(this, list);
		// adapter = new SimpleAdapter(this, list,
		// R.layout.activity_comment_item,
		// new String[] { "icon", "name", "content", "date" }, new int[] {
		// R.id.pic, R.id.name, R.id.comment_content,
		// R.id.comment_date });
		// adapter.setViewBinder(new BitmapViewBinder());
		listView.setAdapter(adapter);
		UiUtils.setListViewHeightBasedOnChildren(listView);
		activityName.setText(intent.getStringExtra("title"));
		activityRequire.setText(intent.getStringExtra("content"));
		Bitmap icon = ImageUtils.drawableToBitmap(getResources().getDrawable(
				R.drawable.m_activity_pic));
		activityPic.setImageBitmap(icon);

		sign.setOnClickListener(this);
		remark.setOnClickListener(this);
		footer.setOnClickListener(this);
		listView.setOnScrollListener(this);

		new AvatarTask().execute(intent.getIntExtra("activityId", 0) + "",
				intent.getStringExtra("picPath"));
		new ActivityDetailTask().execute(intent.getIntExtra("activityId", 0));
	}

    public ListView getListView(){
        return this.listView;
    }

	@Override
	public void onClick(View v) {
		if (v == sign) {
			UiUtils.showToast(this,
					"报名成功。详细内容及最终中选情况\n请登录www.moorecat.com活动专区查询");
		} else if (v == remark) {
			Intent intent = new Intent(this, Comment.class);

		}

	}

	public class ActivityDetailTask extends
			AsyncTask<Integer, Integer, List<com.moorecat.bean.Comment>> {

		private boolean isException;

		@Override
		protected List<com.moorecat.bean.Comment> doInBackground(
				Integer... params) {
			List<com.moorecat.bean.Comment> list = null;
			try {
				list = HttpUtils
						.fetchShopActivityCommentList(params[0], 0, 100);
				for (com.moorecat.bean.Comment comment : list) {
					comment.getUser().setIcon(mooerApp.getAvatarIcon());
				}
			} catch (Exception e) {
				isException = true;
				e.printStackTrace();
			}
			return list;
		}

		@Override
		protected void onPostExecute(List<com.moorecat.bean.Comment> result) {
			super.onPostExecute(result);
			if (isException) {
				footer.setVisibility(View.GONE, View.GONE, View.VISIBLE,
						View.VISIBLE);
			} else {
				if (result.size() > 0) {
					list.addAll(result);
					listView.removeFooterView(footer);
					adapter.notifyDataSetChanged();
					UiUtils.setListViewHeightBasedOnChildren(listView);
					bitmapTask = new BitmapTask().execute("");
				} else {
					footer.setVisibility(View.GONE, View.GONE, View.VISIBLE,
							View.GONE);
					footer.setText(null, "本活动暂无评论");
				}
			}
		}
	}

	private class AvatarTask extends AsyncTask<String, Integer, Bitmap> {

		@Override
		protected Bitmap doInBackground(String... params) {
			Bitmap bitmap = null;
			bitmap = HttpUtils.downloadBitmap(params[1]);
			return bitmap;
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			super.onPostExecute(result);
			if (result != null) {
				activityPic.setImageBitmap(result);
			}
		}

	}

	private class BitmapTask extends AsyncTask<String, Integer, String> {

		@Override
		protected String doInBackground(String... params) {
			long id = System.currentTimeMillis();
			taskId = id;
			// 增加一个缓存List避免列表长度变化时遍历发生错误
			List<com.moorecat.bean.Comment> cacheList = new ArrayList<com.moorecat.bean.Comment>();
			cacheList.addAll(list);
			Iterator<com.moorecat.bean.Comment> it = cacheList.iterator();
			while (it.hasNext()) {
				/*
				 * 避免重复下载,如果有新的线程,则停止老的线程
				 */
				if (id != taskId || isCancelled) {
					break;
				}
				com.moorecat.bean.Comment comment = it.next();
				Bitmap icon = null;
				try {
					if (comment.getUser().getIcon() == mooerApp.getAvatarIcon()) {
						icon = HttpUtils.downloadBitmap(comment.getUser()
								.getPhoto());
						if (icon != null) {
							comment.getUser().setIcon(icon);
							publishProgress(0);
						}
					}
				} catch (Exception e) {

				}
			}
			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			adapter.notifyDataSetChanged();
		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (bitmapTask != null) {
			boolean isSuccess = bitmapTask.cancel(true);
			Log.i(TAG, "BitmapTask cancelled " + isSuccess);
			isCancelled = true;
		}
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		System.out.println("----------------------");
	}

}
